<template>
  <div class="home-container">
    <form action="/" class="form">
      <van-search
        v-model="searchText"
        show-action
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <searchResult v-if="isResultShow" :search-text="searchText"/>
     <!-- 联想建议 -->
    <searchSuggest v-else-if="searchText" :search-text="searchText" @onSearch ="onSearch"/>
    <!-- 搜索历史 -->
    <searchHistory v-else :searchHistory="searchHistory" @clearSearchHistory="searchHistory = []" @onSearch="onSearch"/>
  </div>
</template>

<script>
import searchHistory from "@/views/search/component/search-history.vue";
import searchSuggest from "@/views/search/component/search-suggest.vue";
import searchResult from "@/views/search/component/search-result.vue";
import { setItem,getItem } from '@/utils/storage.js'
export default {
  components: {
    searchHistory,
    searchSuggest,
    searchResult,
  },
  watch:{
    searchHistory:{
      handler(value){
        // console.log(111)
      setItem('HEIMA_TOUTIAO',value)
      },
      immediate:true
    }
  },
  data() {
    return {
      searchText: "",
      isResultShow:false,//控制搜索结果的显示
      searchHistory:getItem('HEIMA_TOUTIAO') || [], //收藏历史记录
    };
  },
  methods: {
    onSearch(val) {
      // 更新文本框的内容
      this.searchText = val;
      // 存储搜索记录,不要有重复的
      const index = this.searchHistory.indexOf(val)
      if(index !== -1){
        this.searchHistory.splice(index,1);
      }
      this.searchHistory.unshift(val)
      // 渲染搜索结果
      this.isResultShow = true;
    },
    onCancel() {
      this.$router.back();
    },
  },

};
</script>

<style scoped lang="less">
  .home-container {
    padding-top: 108px;
    .van-search {
      .van-search__action{
        color: #fff;
      }
    };
    .form {
      width: 100%;
      position: fixed;
      top: 0;
      right: 0;
      z-index: 1;
    }
    
  }
</style>